package dry.example.gui;

import javax.swing.*;
import java.awt.*;

public class SpringLayoutDemo {
    public static void main(String[] args) {
        // 创建主窗口
        JFrame frame = new JFrame("SpringLayout 示例");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);

        // 创建 JPanel 并设置为 SpringLayout
        JPanel panel = new JPanel(new SpringLayout());

        // 创建组件
        JLabel userLabel = new JLabel("用户名:");
        JTextField userField = new JTextField(15); // 设置宽度为15字符宽

        JLabel passLabel = new JLabel("密码:");
        JPasswordField passField = new JPasswordField(15);

        JButton loginButton = new JButton("登录");
        JButton cancelButton = new JButton("取消");

        // 添加组件到面板
        panel.add(userLabel);
        panel.add(userField);
        panel.add(passLabel);
        panel.add(passField);
        panel.add(loginButton);
        panel.add(cancelButton);

        // 获取 SpringLayout 实例
        SpringLayout layout = (SpringLayout) panel.getLayout();

        // 设置约束条件
        int labelWidth = 60; // 标签宽度统一

        // 第一行：用户名标签和输入框
        layout.putConstraint(SpringLayout.WEST, userLabel, 10, SpringLayout.WEST, panel);
        layout.putConstraint(SpringLayout.NORTH, userLabel, 10, SpringLayout.NORTH, panel);
        layout.putConstraint(SpringLayout.EAST, userField, -10, SpringLayout.EAST, panel);
        layout.putConstraint(SpringLayout.NORTH, userField, 10, SpringLayout.NORTH, panel);
        layout.putConstraint(SpringLayout.WEST, userField, 10, SpringLayout.EAST, userLabel);

        // 第二行：密码标签和输入框
        layout.putConstraint(SpringLayout.WEST, passLabel, 10, SpringLayout.WEST, panel);
        layout.putConstraint(SpringLayout.NORTH, passLabel, 10, SpringLayout.SOUTH, userLabel);
        layout.putConstraint(SpringLayout.EAST, passField, -10, SpringLayout.EAST, panel);
        layout.putConstraint(SpringLayout.NORTH, passField, 10, SpringLayout.SOUTH, userField);
        layout.putConstraint(SpringLayout.WEST, passField, 10, SpringLayout.EAST, passLabel);

        // 第三行：按钮
        layout.putConstraint(SpringLayout.WEST, loginButton, 10, SpringLayout.WEST, panel);
        layout.putConstraint(SpringLayout.NORTH, loginButton, 20, SpringLayout.SOUTH, passLabel);

        layout.putConstraint(SpringLayout.EAST, cancelButton, -10, SpringLayout.EAST, panel);
        layout.putConstraint(SpringLayout.NORTH, cancelButton, 20, SpringLayout.SOUTH, passLabel);

        // 设置按钮之间的水平间距
        layout.putConstraint(SpringLayout.WEST, cancelButton, 10, SpringLayout.EAST, loginButton);

        // 将面板加入窗口
        frame.add(panel);
        frame.setVisible(true);
    }
}
